import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import { getToken, relogin } from '@/utils/util.js'

let time = null; // 保存请求时的定时器,做一个节流操作,避免多次触发弹窗
let qttoken = localStorage.getItem("qtToken")
const service = axios.create({
  baseURL: '/basic-api/srs-business-api',
  timeout: 40000, //超时时间
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'X-Base-Token': qttoken, // 挂载qtToken
  }
})

// 请求拦截
service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers['Authorization'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  if ((config.method === "post" || config.method === "put") && config.isFormData) {
    config.headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
    config.data = qs.stringify(config.data);
  } else if (config.method === 'get' || config.method === 'delete') {
    config.url += ('?' + qs.stringify(config.data))
  }
  return config
}, error => {
  console.log(error) // for debug
  Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(response => {
  if (response.code == 401) {
    if(time) return;
    Message.error("您需要登录才能访问当前页面，请先登录")
    time = setTimeout(()=>{
        relogin()
        time = null;
      },500)
    return;
  }else if(response.code == 402){
    setTimeout(()=>{
      relogin()
    },500)
    return;
  }
  return response.data;
}, error => {
  console.log('err' + error) // for debug
  let { message } = error
  if(message == "Network Error") {
    message = "后端接口连接异常"
  } else if(message.includes("timeout")) {
    message = "系统接口请求超时"
  } else if(message.includes("Request failed with status code")) {
    message = "系统异常，请稍后重试"
  }
  Message.error(message)
  return Promise.reject(error)
})
export default service